<?php
declare(strict_types=1);
/**
 * Created by PhpStorm
 * User: Administrator
 * Date: 2023/8/18
 * Time: 14:33:43
 */

namespace Service\WebSocketService;

use App\Model\BbcModel\GoodsClass;
use Service\Code\Normal;
use Service\ExportService\ExportExcelHandle;

class GoodsClassService extends BaseWsService
{
    /**
     * 商品分类导出
     * @param $server
     * @param int $fd
     * @param array $body
     * @param int $manager_id
     * @param int $cid
     * @return array
     */
    public function export($server, int $fd, array $body, int $manager_id, int $cid)
    {
        ini_set('memory_limit', '3096M');
        $param        = $body;
        $param['cid'] = $cid;

        $whereRaw = (new \Service\CommodityService\GoodsClassService())->makeWhere($param);

        if ($server) {
            $send = Normal::returnCode(Normal::WS_START, "进行中", [
                'percent' => 20,
            ]);
            $server->push($fd, json_encode($send, JSON_UNESCAPED_UNICODE));
        }

        $data_list = GoodsClass::instance()
            ->where($whereRaw)
            ->select(['id','name','pid','icon','md','show'])
            ->get()->toArray();

        $all_list = GoodsClass::instance()
            ->where(['cid'=>$cid,'df'=>0])
            ->select(['id','name'])
            ->get()->toArray();
        $all_list_map = array_column($all_list,null,'id');
        foreach ($data_list as &$v){
            if($v['md']){
                $v['md'] = date('Y-m-d H:i:s',$v['md']);
            }

            if($v['cd']){
                $v['cd'] = date('Y-m-d H:i:s',$v['cd']);
            }

            if($v['pid'] == 0){
                $v['pid'] = $all_list_map[$v['pid']] ?? '';
            }else{
                $v['pid'] = '顶级分类';
            }

            if($v['show'] == 1){
                $v['show'] = '是';
            }else{
                $v['show'] = '否';
            }
        }

        $data['header'] = [
            'id', '名称', '上级分类','图标','更新时间','是否显示',
        ];

        $data['fileName'] = '商品分类.xlsx';
        $data['data']     = $data_list;
        $exportRes        = ExportExcelHandle::instance()->uploadAliOssSource($data['fileName'], $data['header'], $data['data']);
        if ($exportRes['code'] != Normal::SUC) {
            return Normal::returnCode(Normal::WS_ERROR, '导出失败:' . $exportRes['msg']);
        }
        return Normal::returnCode(Normal::WS_END, "已完成", [
            'percent'      => 100.00,
            'download_url' => $exportRes['data']['path'],
        ]);
    }
}